//
//  PlaceInfoViewController.m
//  翼安保
//
//  Created by duzhi on 2025/9/15.
//

#import "PlaceInfoViewController.h"
#import "regular.h"
#import "LoginApi.h"
#import "AddressModel.h"
#import "AddressView.h"

@interface PlaceInfoViewController ()
@property (nonatomic ,strong) UIView  *contentView;
@property (nonatomic, strong) NSString      *pCode;
@property (nonatomic, strong) NSString      *cCode;
@property (nonatomic, strong) NSString      *dCode;
@property (nonatomic, strong) AddressView   *addressView;
@property (nonatomic, strong) NSArray       *cityInfos;
@property (nonatomic, strong) NSMutableArray *tasks;
@end

@implementation PlaceInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    [self getCityInfos:nil];
    [self getPlaceInfos];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)back {
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)creatUI {
    NewsBigButton *backButton = [NewsBigButton new];
    [backButton setBackgroundImage:[UIImage imageNamed:@"back_black_26x26"] forState:0];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(15));
        make.centerY.mas_equalTo(self.view.mas_top).mas_offset(kiPhoneX_Top_Height+relativeWidth(22));
    }];
    
    UIView *scrollView = [UIView new];
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
    scrollView.layer.shadowOffset = CGSizeMake(0,0);
    scrollView.layer.shadowOpacity = 0.3;
    scrollView.layer.shadowRadius = relativeWidth(2);
    scrollView.layer.masksToBounds = NO;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(30));
        make.right.mas_equalTo(relativeWidth(-30));
        make.top.mas_equalTo(kiPhoneX_Top_Height + 64);
        make.bottom.mas_equalTo(-kiPhoneX_Top_Height - 64);
    }];
    self.contentView = scrollView;
    
    UILabel *titleL = [UILabel new];
    titleL.text = @"修改所属区域";
    titleL.font = [UIFont boldSystemFontOfSize:relativeWidth(20)];
    titleL.textColor = [UIColor blackColor];
    [self.contentView addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(relativeWidth(20));
    }];
    
    UILabel *tipL = [UILabel new];
    tipL.text = @"人信息修改仅限于修改所属地区";
    tipL.font = [UIFont systemFontOfSize:relativeWidth(13)];
    tipL.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self.contentView addSubview:tipL];
    [tipL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(titleL.mas_bottom).offset(relativeWidth(10));
    }];
    
    UIView *theLastInputView = nil;
    for (int i=0; i<5; i++) {
        UIView *inputView = [self creatInputView:i];
        [inputView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(tipL.mas_bottom).offset(relativeWidth(20)+i*relativeWidth(60));
            make.height.mas_equalTo(relativeWidth(60));
        }];
        theLastInputView = inputView;
    }
    
    UIButton *registerButton = [UIButton new];
    registerButton.backgroundColor = UIColorFromRGB(0x1196db);
    [registerButton setTitle:@"立即更新" forState:0];
    registerButton.layer.cornerRadius = relativeWidth(22);
    [registerButton setTitleColor:[UIColor whiteColor]  forState:0];
    [registerButton addTarget:self action:@selector(registerClick) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:registerButton];
    [registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(relativeWidth(relativeWidth(-40)));
        make.height.mas_equalTo(relativeWidth(44));
        make.left.mas_equalTo(relativeWidth(40));
        make.top.mas_equalTo(theLastInputView.mas_bottom).offset(relativeWidth(60));
    }];
    
    self.addressView = [AddressView new];
    self.addressView.backgroundColor = [UIColor whiteColor];
    self.addressView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, relativeWidth(200));
    self.addressView.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
    self.addressView.layer.shadowOffset = CGSizeMake(0,0);
    self.addressView.layer.shadowOpacity = 0.3;
    self.addressView.layer.shadowRadius = relativeWidth(2);
    Weak(wself, self)
    self.addressView.confirmBlock = ^(AddressModel * _Nonnull p, ChooseAreaListCityModel * _Nonnull c, ChooseAreaListDistrictModel * _Nonnull d) {
        UITextField *t = [wself.contentView viewWithTag:10004];
        t.text = [NSString stringWithFormat:@"%@%@%@",p.Description,c.Description,d.Description];
        wself.pCode = p.ID;
        wself.cCode = c.ID;
        wself.dCode = d.ID;
    };
    [self.view addSubview:self.addressView];
}

- (UIView *)creatInputView:(int)type {
    UIView *inputView = [UIView new];
    inputView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:inputView];
    
    UILabel *nameL = [UILabel new];
    nameL.textColor = [UIColor blackColor];
    nameL.font = [UIFont systemFontOfSize:relativeWidth(14)];
    [inputView addSubview:nameL];
    CGFloat w = [@"管理员手机号码" sizeWithFont:nameL.font maxWidth:1000].width+1;
    [nameL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(20));
        make.width.mas_equalTo(w);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(relativeWidth(60));
    }];
    
    UITextField *phoneTextField = [UITextField new];
    phoneTextField.userInteractionEnabled = NO;
    phoneTextField.font         = [UIFont systemFontOfSize:relativeWidth(14)];
    phoneTextField.tintColor    = [UIColor blackColor];
    phoneTextField.tag          = 10000+type;
    [self.contentView addSubview:phoneTextField];
    [phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(nameL.mas_right).offset(relativeWidth(10));
        make.right.mas_equalTo(relativeWidth(-20));
        make.height.mas_equalTo(nameL);
        make.centerY.mas_equalTo(inputView);
    }];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    [self.contentView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(nameL);
        make.right.mas_equalTo(phoneTextField);
        make.top.mas_equalTo(inputView.mas_bottom).mas_offset(-0.5);
        make.height.mas_equalTo(0.5);
    }];
    NSString *placeHolder = @"";
    switch (type) {
        case 0:
            placeHolder = @"姓名";
            break;
        case 1:
            placeHolder = @"手机号码";
            break;
        case 2:
            placeHolder = @"公司名称";
            break;
        case 3:
            placeHolder = @"管理员手机号";
            break;
        case 4:
            placeHolder = @"所属区域";
            break;
            
        default:
            break;
    }
    phoneTextField.placeholder  = placeHolder;
    nameL.text = placeHolder;
    
    if (type == 4) {
        inputView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickPlace)];
        [inputView addGestureRecognizer:tap];
    }
    return inputView;
}


- (void)registerClick {
    if (allTrim(self.pCode).length == 0||allTrim(self.cCode).length == 0||allTrim(self.dCode).length == 0) {
        [MBProgressHUD showTextHUD:@"请选择地区,精确到区/县" superView:self.view];
        return;
    }
    [self registerApi];
}

- (void)clickPlace {
    [self.view endEditing:YES];
    if (!self.cityInfos) {
        [self getCityInfos:^{
            [self showAddress];
        }];
    }else {
        [self showAddress];
    }
}

- (void)showAddress {
    self.addressView.datas = self.cityInfos;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.addressView.frame = CGRectMake(0, ScreenHeight-relativeWidth(200), ScreenWidth, relativeWidth(200));
    } completion:nil];
}

#pragma mark api
- (void)registerApi {
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"fProvinceCode"] = self.pCode;
    dic[@"fCityCode"] = self.cCode;
    dic[@"fAreaCode"] = self.dCode;
    NSLog(@"参数:%@",dic);
    [[AFNNetWorkManager shareAFNNetWorkManager] postJson:updateArea parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
        NSLog(@"%ld",(long)result.code);
        if (result.code == 200) {
            [MBProgressHUD showTextHUD:@"修改成功"];
            [self back];
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

- (void)getCityInfos:(void (^)(void))complete {
    //取消上一次请求
    NSMutableArray *canceTasks = [NSMutableArray new];
    [self.tasks enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSURLSessionDataTask *task = obj;
        if (task.state != NSURLSessionTaskStateCompleted) {
            [task cancel];
            [canceTasks addObject:task];
        }
    }];
    [self.tasks removeObjectsInArray:canceTasks];
    NSURLSessionDataTask *task = [[AFNNetWorkManager shareAFNNetWorkManager] Get:cityInfoUrl parameters:nil success:^(NSURLSessionDataTask *task, Result *result) {
        if (result.code == 200) {
            self.cityInfos = [AddressModel mj_objectArrayWithKeyValuesArray:result.data];
            if ((complete)) {
                complete();
            }
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
    }];
    if (task.state != NSURLSessionTaskStateCompleted && self.tasks) {
        [self.tasks addObject:task];
    }
}

- (void)getPlaceInfos {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFNNetWorkManager shareAFNNetWorkManager] Get:queryRegisterInfo parameters:nil success:^(NSURLSessionDataTask *task, Result *result) {
        [hud hideAnimated:YES];
        if (result.code == 200) {
            NSLog(@"拿到的信息：%@==%@",[result.data class],result.data);
            if ([result.data isKindOfClass:[NSDictionary class]]) {
                NSDictionary *info = result.data;
                if ([info.allKeys containsObject:@"fName"]) {
                    UITextField *t = [self.contentView viewWithTag:10000];
                    t.text = [NSString stringWithFormat:@"%@",info[@"fName"]];
                }
                if ([info.allKeys containsObject:@"fPhone"]) {
                    UITextField *t = [self.contentView viewWithTag:10001];
                    t.text = [NSString stringWithFormat:@"%@",info[@"fPhone"]];
                }
                if ([info.allKeys containsObject:@"fCompanyName"]) {
                    UITextField *t = [self.contentView viewWithTag:10002];
                    t.text = [NSString stringWithFormat:@"%@",info[@"fCompanyName"]];
                }
                if ([info.allKeys containsObject:@"fManagerPhone"]) {
                    UITextField *t = [self.contentView viewWithTag:10003];
                    t.text = [NSString stringWithFormat:@"%@",info[@"fManagerPhone"]];
                }
                
                if ([info.allKeys containsObject:@"fProvinceCode"]) {
                    self.pCode = info[@"fProvinceCode"];
                }
                if ([info.allKeys containsObject:@"fCityCode"]) {
                    self.cCode = info[@"fCityCode"];
                }
                if ([info.allKeys containsObject:@"fAreaCode"]) {
                    self.dCode = info[@"fAreaCode"];
                }
                if (self.pCode||self.dCode||self.cCode) {
                    void (^setPlaceInfoBlock)(void) = ^(){
                        UITextField *t = [self.contentView viewWithTag:10004];
                        NSString *placeStr = @"";
                        NSArray *resultArray = nil;
                        int findCout = 0;
                        for (AddressModel *model in self.cityInfos) {
                            if ([model.ID isEqualToString:self.pCode]) {
                                placeStr = model.Description;
                                resultArray = model.children;
                                findCout++;
                            }
                        }
                        if (findCout == 0) {
                            t.text = placeStr;
                            return;
                        }
                        
                        for (ChooseAreaListCityModel *model in resultArray) {
                            if ([model.ID isEqualToString:self.cCode]) {
                                placeStr = [NSString stringWithFormat:@"%@%@",placeStr,model.Description];
                                resultArray = model.children;
                                findCout++;
                            }
                        }
                        if (findCout == 1) {
                            t.text = placeStr;
                            return;
                        }
                        
                        for (ChooseAreaListDistrictModel *model in resultArray) {
                            if ([model.ID isEqualToString:self.dCode]) {
                                placeStr = [NSString stringWithFormat:@"%@%@",placeStr,model.Description];
                            }
                        }
                        t.text = placeStr;
                    };
                    if (!self.cityInfos) {
                        [self getCityInfos:^{
                            setPlaceInfoBlock();
                        }];
                    }else {
                        setPlaceInfoBlock();
                    }
                }
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [hud hideAnimated:YES];
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

@end
